package example.core.router;

import com.aliyun.fc.runtime.Context;
import example.core.controller.ControllerMateData;
import example.core.controller.ControllerMateUtil;
import example.core.filter.FcWebFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * 实现一个路由到Controller路由。
 */
@Component
public class ControllerRouter implements Router {

    /**
     * 过滤器配置
     */
    @Autowired(required = false)
    FcWebFilter fcWebFilter;

    @Override
    public Object urlRouter(HttpServletRequest request, HttpServletResponse response, Context context) {
        try{
            String requestPath = (String) request.getAttribute("FC_REQUEST_PATH");
            String requestURI = (String) request.getAttribute("FC_REQUEST_URI");
            String requestClientIP = (String) request.getAttribute("FC_REQUEST_CLIENT_IP");
            if (StringUtils.isEmpty(requestPath)) {
                requestPath = request.getServletPath();
            }
            ControllerMateData controllerMateData = ControllerMateUtil.getMapper(requestPath);
            ControllerMateUtil.runMethod(controllerMateData, "{\"FC_REQUEST_PATH\": \"url\"}");
            response.setStatus(200);
            response.setHeader("header1", "value1");
            response.setHeader("header2", "value2");
            response.setHeader("Content-Type", "text/plain");
            context.getLogger().info("http请求");
            String body = String.format("Path: %s\n Uri: %s\n IP: %s\n", requestPath, requestURI, requestClientIP);
            OutputStream out = response.getOutputStream();
            out.write((body).getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
